package com.suemi.missile.plugin.executors;

import com.suemi.missile.common.mql.query.MqlElasticRequestBuilder;
import com.suemi.missile.common.mql.query.QueryAction;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.action.RestStatusToXContentListener;

import java.util.Map;

public class RestMqlExecutor implements RestExecutor {

  public RestMqlExecutor() {

  }

  @Override
  public void execute(Client client, Map<String, String> params, QueryAction queryAction, RestChannel channel) throws Exception {
    MqlElasticRequestBuilder requestBuilder = queryAction.explain();
    ActionRequest request = requestBuilder.request();

    if (request instanceof SearchRequest) {
      client.search((SearchRequest) request, new RestStatusToXContentListener<SearchResponse>(channel));
    } else {
      throw new Exception(String.format("Unsupported ActionRequest provided: %s", request.getClass().getName()));
    }
  }

  @Override
  public String execute(Client client, Map<String, String> params, QueryAction queryAction) throws Exception {
    MqlElasticRequestBuilder requestBuilder = queryAction.explain();
    ActionRequest request = requestBuilder.request();

    if (request instanceof SearchRequest) {
      ActionFuture<SearchResponse> future = client.search((SearchRequest) request);
      SearchResponse response = future.actionGet();
      return response.toString();
    } else {
      throw new Exception(String.format("Unsupported ActionRequest provided: %s", request.getClass().getName()));
    }

  }
}
